const db = wx.cloud.database()
import { get, add } from "../../utils/db";
import { upload, multiUpload } from "../../utils/upload";

const app = getApp()
Page({
  data: {
    typeList: [],    //分类列表
    files: [],       //临时图片地址

  },
  //页面加载的时候，读取type集合中的数据，渲染到页面
  async onLoad() {
    let result = await get({
      collection: "type",
      limit: 10,
      skip: 0,
      where: {}
    }).catch(err => {
      console.error(err)
    })

    this.setData({
      typeList: result.data
    })
  },
  //提交表单
  async handleSubmit(e) {

    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    //获取图片临时地址
    let arr = this.data.files

    //批量上传
    let image = await multiUpload(arr).catch(err => console.error(err))

    //整理表单数据
    let { name, typeid, info } = e.detail.value;
    let { avatarUrl, nickName } = app.globalData.userInfo;
    let views = 0;
    let likes = 0;
    let addtime = new Date().getTime()
    //执行添加
    let result = await add({
      collection: "menu",
      data: { name, avatarUrl, info, nickName, typeid, image, views, likes, addtime }
    }).catch(err => {
      console.error(err)
    })
    //隐藏loading框
    wx.hideLoading()    
    wx.navigateBack({
      delta: 1,
    })
  },
  //选择相册里面的图片
  handleSelect(e) {
    let arr = e.detail.tempFilePaths;   //图片数组
    //把字符串数组转化成对象数组 

    let files = arr.map(item => {
      return { url: item }
    })
    this.setData({
      files
    })

  }


})